package cn.wolfcode.shop.cloud.service.impl;

import cn.wolfcode.shop.cloud.BusinessException;
import cn.wolfcode.shop.cloud.RedisService;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.mapper.UserMapper;
import cn.wolfcode.shop.cloud.msg.MemberCodeMsg;
import cn.wolfcode.shop.cloud.service.IUserService;
import cn.wolfcode.shop.cloud.util.MD5Util;
import cn.wolfcode.shop.cloud.util.MemberKeyPrefix;
import cn.wolfcode.shop.cloud.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public User findById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public String doLogin(LoginVO vo) {
        String username = vo.getUsername();
        Long id = Long.valueOf(username);
        User user = userMapper.findById(id);
        if (user == null) {
            throw new BusinessException(MemberCodeMsg.USER_NOT_EXISTS);
        }

        String pass = MD5Util.encode(vo.getPassword(), user.getSalt());
        if (!pass.equals(user.getPassword())) {
            throw new BusinessException(MemberCodeMsg.PASSWORD_ERROR);
        }

        String token = UUID.randomUUID().toString().replace("-", "");
        redisService.set(MemberKeyPrefix.USER_TOKEN, token, user);


        return token;

    }

    @Override
    public boolean refreshTime(String token) {
        //1 判断之前redis当中是都有token
        if (redisService.exists(MemberKeyPrefix.USER_TOKEN, token)) {
            //2 如果有的话延长过期时间
            redisService.expire(MemberKeyPrefix.USER_TOKEN, token, MemberKeyPrefix.USER_TOKEN.getExpireTime());
            return true;
        }

        return false;
    }

    @Override
    public User getCurrent(String token) {
        return redisService.get(MemberKeyPrefix.USER_TOKEN, token, User.class);
    }


}
